package com.yupi.yupicturebackend.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.yupi.yupicturebackend.manager.auth.SpaceUserAuthManager;
import com.yupi.yupicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.SpaceTypeEnum;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import groovyjarjarantlr4.v4.runtime.misc.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) {
        // 获取请求用户
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 获取图片id,校验参数
            String pictureId = httpServletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)) {
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            User user = userService.getLoginUser(httpServletRequest);
            if (ObjUtil.isNull(user)) {
                log.error("用户未登录，拒绝握手");
                return false;
            }
            // 查看用户是否有权限
            Picture picture = pictureService.getById(pictureId);
            if (ObjUtil.isNull(picture)) {
                log.error("图片不存在，拒绝握手");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space =null;
            if(spaceId != null){
                space = spaceService.getById(spaceId);
                if(space == null){
                    log.error("空间不存在，拒绝握手");
                    return false;
                }
                if(!space.getSpaceType().equals(SpaceTypeEnum.TEAM.getValue())){
                    log.error("非团队空间，拒绝握手");
                    return false;
                }
            }
            // 如果是团队空间，且用户为编辑者，则建立连接
            List<String> permissions = spaceUserAuthManager.getPermissionList(space, user);
            if (space != null && !permissions.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("用户无编辑权限，拒绝握手");
                return false;
            }
            // 设置用户登录信息到webSocket中
            attributes.put("user", user);
            attributes.put("userId", user.getId());
            attributes.put("pictureId", Long.valueOf(pictureId));     // 图片id转化为long类型
        }
        return true;
    }

    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {
    }
}
